package com.xxl.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import static java.lang.System.out;

/**
 * 路由用于跳转
 *
 * @author xxl
 * @date 2023/3/12
 */
@Controller
@RequestMapping("view")
public class RouteController {
    @GetMapping({"/common.html/{text}", "/login.html"})
    public String common(
            @PathVariable(value = "text", required = false) String text
            , Model model) {
        out.println("处理请求");
        if (StringUtils.isEmpty(text)) {
            return "/view/login";
        }
        model.addAttribute("msg", text);
        return "/common/common";
    }
    @Resource
    private HttpSession session;
    @GetMapping("/user/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        out.println(subject.toString());
        //封装用户登录信息
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        out.println(token);
        try {
            //执行登录，没有异常则正常
            subject.login(token);
            out.println("登录成功后="+subject.getPrincipal());
            session.setAttribute("userInfo",subject.getPrincipal());
        } catch (UnknownAccountException e) {
            //账户不正确
            model.addAttribute("msg", "账户不存在");
            //转发给控制器处理
            return "forward:/view/login.html";
        } catch (IncorrectCredentialsException e) {
            //密码不正确
            model.addAttribute("msg", "密码不正确");
            return "forward:/view/login.html";
        }

        return "/index";
    }

    @GetMapping("/home")
    public String home() {
        return "/view/home";
    }

    @GetMapping("/unauthorized")
    public String unauthorized() {
        return "/view/unauthorized";
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        out.println("注销前"+subject.getPrincipal());
        subject.logout();
        out.println("注销后="+subject.getPrincipal());
        return "/index";
    }
}
